package com.example.martian.service;

import com.example.martian.config.util.RedisUtils;
import com.example.martian.mapper.AuthenticationMapper;
import com.example.martian.mapper.IndexMapper;
import com.example.martian.mapper.RedPacketMapper;
import com.example.martian.utils.BigDecimalUtils;
import com.example.martian.utils.RedPacketMessage;
import com.example.martian.utils.RedPacketQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * 延迟队列过期消费
 */
@Component
public class TaskRunner implements ApplicationRunner {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private IndexMapper indexMapper;

    @Autowired
    private RedPacketMapper redPacketMapper;

    @Autowired
    private AuthenticationMapper authenticationMapper;

    private final static Logger LOGGER = LoggerFactory.getLogger(TaskRunner.class);

    ExecutorService executorService = Executors.newSingleThreadExecutor(r -> {
        Thread thread = new Thread(r);
        thread.setName("RedPacketDelayWorker");
        thread.setDaemon(true);
        return thread;
    });

    @Override
    public void run(ApplicationArguments var){
        executorService.execute(() -> {
            while (true) {
                try {
                    RedPacketMessage message = RedPacketQueue.getQueue().consume();
                    System.out.println(message);
                    if(message!=null){
                        String address = "";
                        String redPacketId = message.getRedPacketId();
                        LOGGER.info("红包{}过期了",redPacketId);
                        List<Map<String,Object>> mapList = redisUtils.getCacheListInMap(redPacketId);
                        for (Map<String,Object> map : mapList){
                            address = map.get("address").toString();
                            String coin = map.get("coin").toString();
                            String value = map.get("value").toString();
                            String moneyCoin = indexMapper.selectMoneyByCoin(coin, address);
                            String addCoinMoney = BigDecimalUtils.add(value, moneyCoin, 8);
                            indexMapper.updateCoinMoney(address, coin, addCoinMoney);
                        }
                        redisUtils.clearPrexCache(redPacketId);
                        redPacketMapper.updateRedPacketZt(1,address,redPacketId);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

}